package com.weiyin.examination.course;

import android.app.Activity;
import android.content.Intent;
import android.os.Handler;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ViewFlipper;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseViewHolder;
import com.weiyin.examination.R;
import com.weiyin.examination.adapter.CourseA3Adapter;
import com.weiyin.examination.application.Constant;
import com.weiyin.examination.dialog.CourseA1Dialog;
import com.weiyin.examination.http.RetrofitClient;
import com.weiyin.examination.listener.CourseInterface;
import com.weiyin.examination.listener.DialogResultInterface;
import com.weiyin.examination.listener.DialogShowListener;
import com.weiyin.examination.module.AnswerModule;
import com.weiyin.examination.module.TestModule;
import com.weiyin.examination.util.LayoutHelper;
import com.weiyin.examination.util.LogUtil;
import com.weiyin.examination.util.SPUtil;
import com.weiyin.examination.view.GridLayoutManager;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author njf
 *         Created by lenovo on 2017/9/18.
 */

public class CourseA3 extends Course implements CourseA3Adapter.OnItemClickInterface {
    private View rootView;

    private Activity activity;
    private ClickAble clickAble;

    private RecyclerView courseA3RecyclerView1, courseA3RecyclerView2;
    private CourseA3Adapter courseA3Adapter2, courseA3Adapter1;

    private TextView titleLayoutNextTextView, titleLayoutLastTextView, titleLayoutSubjectContentTextView,
            titleLayoutSubjectScoreTextView, titleLayoutNumberTextView, titleTicketNumber;
    private RelativeLayout titleLayoutNumberRl, courseA3Rl;
    private ImageView courseA3ImageView1, courseA3ImageView2;

    private TestModule testModule;
    private List<TestModule> testModuleList;
    private List<AnswerModule> answerModuleList;
    private int courseIndex, intNumber1 = 0, intNumber2 = 0;
    private String[] imageUrl;
    private Handler mHandler = new Handler();
    private List<String> line1, line2;
    LayoutHelper layoutHelper;
    private Map<String, String> map;
    private double score;

    @Override
    public void onCreate(Activity activity, ViewFlipper contain, List<TestModule> courseEntities, int index) {
        if (rootView == null) {
            rootView = LayoutInflater.from(activity).inflate(R.layout.coursea3_layout, null);
            layoutHelper = new LayoutHelper(activity);
            layoutHelper.scaleView(rootView);

            contain.addView(rootView);
            this.testModuleList = courseEntities;
            this.activity = activity;
            this.courseIndex = index;
            this.testModule = testModuleList.get(index);
            map = new HashMap<>();
            clickAble = new ClickAble();
            if (line1 == null) {
                line1 = new ArrayList<>();
            }
            if (line2 == null) {
                line2 = new ArrayList<>();
            }
            if (testModule != null) {
                getImageUrl();
                if (testModule.getRightAnswerList() != null) {
                    this.answerModuleList = testModule.getRightAnswerList();
                    getLineNumber();
                }
            }

            initView();
        }
    }

    private void getImageUrl() {
        if (testModule.getSubjectUrl() != null) {
            if (testModule.getSubjectUrl().contains(Constant.SUBJECT_URL_CONTAINS)) {
                int stringIndex = testModule.getSubjectUrl().indexOf(Constant.SUBJECT_URL_CONTAINS);
                imageUrl = new String[2];
                imageUrl[0] = testModule.getSubjectUrl().substring(0, stringIndex);
                imageUrl[1] = testModule.getSubjectUrl().substring(stringIndex + 1);

                LogUtil.i(TAG, imageUrl[0]);
                LogUtil.i(TAG, imageUrl[1]);
            } else {
                imageUrl = new String[1];
                imageUrl[0] = testModule.getSubjectUrl();
                LogUtil.i(TAG, imageUrl[0]);
            }
        }
    }

    private void getLineNumber() {
        if (answerModuleList != null) {
            for (int i = 0; i < answerModuleList.size(); i++) {
                AnswerModule answerModule = answerModuleList.get(i);
                if ("1".equals(answerModule.getLineNumber())) {
                    intNumber1++;
                    line1.add(i + "");
                } else if ("2".equals(answerModule.getLineNumber())) {
                    intNumber2++;
                    line2.add(i + "");
                }
            }
        }
    }

    @Override
    public void initView() {
        titleLayoutNextTextView = (TextView) rootView.findViewById(R.id.titleLayoutNextTextView);
        titleLayoutLastTextView = (TextView) rootView.findViewById(R.id.titleLayoutLastTextView);
        titleLayoutSubjectContentTextView = (TextView) rootView.findViewById(R.id.titleLayoutSubjectContentTextView);
        titleLayoutSubjectScoreTextView = (TextView) rootView.findViewById(R.id.titleLayoutSubjectScoreTextView);
        titleLayoutNumberTextView = (TextView) rootView.findViewById(R.id.titleLayoutNumberTextView);
        courseA3ImageView1 = (ImageView) rootView.findViewById(R.id.courseA3ImageView1);
        courseA3ImageView2 = (ImageView) rootView.findViewById(R.id.courseA3ImageView2);
        titleTicketNumber = (TextView) rootView.findViewById(R.id.titleTicketNumber);
        courseA3Rl = (RelativeLayout) rootView.findViewById(R.id.courseA3Rl);
        titleLayoutNumberRl = (RelativeLayout) rootView.findViewById(R.id.titleLayoutNumberRl);

        courseA3RecyclerView1 = (RecyclerView) rootView.findViewById(R.id.courseA3RecyclerView1);
        courseA3Adapter1 = new CourseA3Adapter(activity, R.layout.coursea3_item_layout, line1);
        courseA3RecyclerView1.setLayoutManager(new GridLayoutManager(activity, intNumber1, LinearLayoutManager.VERTICAL, false));
        courseA3RecyclerView1.setAdapter(courseA3Adapter1);
        courseA3Adapter1.setOnItemClickInterface(this);

        courseA3RecyclerView2 = (RecyclerView) rootView.findViewById(R.id.courseA3RecyclerView2);
        courseA3Adapter2 = new CourseA3Adapter(activity, R.layout.coursea3_item_layout, line2);
        courseA3RecyclerView2.setLayoutManager(new GridLayoutManager(activity, intNumber2, LinearLayoutManager.VERTICAL, false));
        courseA3RecyclerView2.setAdapter(courseA3Adapter2);
        courseA3Adapter2.setOnItemClickInterface(this);

        titleLayoutNextTextView.setOnClickListener(clickAble);
        titleLayoutLastTextView.setOnClickListener(clickAble);
        titleLayoutNumberRl.setOnClickListener(clickAble);
    }

    private void initViewData() {
        if (testModule != null) {
            titleTicketNumber.setText("准考证号：" + "" + testModule.getTickNumber());

            titleLayoutLastTextView.setVisibility(courseIndex == 0 ? View.GONE : View.VISIBLE);
            titleLayoutNextTextView.setVisibility(courseIndex == testModuleList.size() - 1 ? View.GONE : View.VISIBLE);
            courseA3ImageView2.setVisibility(intNumber2 == 0 ? View.GONE : View.VISIBLE);

            titleLayoutSubjectContentTextView.setText((courseIndex + 1) + "丶" + testModule.getSubjectTitle());
            titleLayoutSubjectScoreTextView.setText("（" + testModule.getScore() + "分）");
            titleLayoutNumberTextView.setText("第" + (courseIndex + 1) + "题/第" + (testModuleList.size()) + "题");
            Glide.with(activity).
                    load(RetrofitClient.BASE_URL + imageUrl[0]).
                    into(courseA3ImageView1);
            if (intNumber2 != 0) {
                Glide.with(activity).
                        load(RetrofitClient.BASE_URL + imageUrl[1]).
                        into(courseA3ImageView2);
            }
        }
    }

    @Override
    public void onItemClick(BaseViewHolder holder, int position, String data) {
        showDialog(holder, position, data);
    }

    private void showDialog(final BaseViewHolder holder, int position, final String data) {
        CourseA1Dialog courseA1Dialog;
        int x = (int) holder.getView(R.id.courseA3ItemLayout).getX() + holder.getView(R.id.courseA3ItemLayout).getWidth() / 2;
        int y;

        if (line1.contains(data)) {
            LogUtil.i(TAG, "1" + data + " " + courseA3RecyclerView1.getTop());
            y = holder.getView(R.id.courseA3ItemLayout).getBottom() + courseA3RecyclerView1.getTop();
        } else {
            LogUtil.i(TAG, "2" + data + "   " + courseA3RecyclerView2.getTop() + "  " + courseA3Rl.getTop());
            y = holder.getView(R.id.courseA3ItemLayout).getBottom() + courseA3RecyclerView2.getTop() + courseA3Rl.getTop();
        }

        courseA1Dialog = new CourseA1Dialog(activity, R.style.BlueToothDialogStyle, testModule);
        Window window = courseA1Dialog.getWindow();
        assert window != null;
        WindowManager.LayoutParams p = window.getAttributes();
        Display d = window.getWindowManager().getDefaultDisplay();
        p.x = x - d.getWidth() / 2 + layoutHelper.scaleDimension(100, "x");
        p.y = y - (d.getHeight() / 2 - layoutHelper.scaleDimension(230 + 150, "y") / 2);
        LogUtil.i(TAG, "x=" + x + " y=" + y);
        window.setAttributes(p);
        courseA1Dialog.setDialogResultInterface(new DialogResultInterface() {
            @Override
            public void result(String type, String result, String answerId) {
                if (Constant.CENTER.equals(type)) {
                    if (result.contains(Constant.INTERVAL_SIGN)) {
                        int index = result.indexOf(Constant.INTERVAL_SIGN);
                        holder.setText(R.id.courseA3ItemTextView1, result.substring(0, index) + "\n" +
                                result.substring(index + 1));
                    } else {
                        holder.setText(R.id.courseA3ItemTextView1, result);
                    }
                    map.put(data + Constant.CENTER, answerId);
                } else if (Constant.LEFT.equals(type)) {
                    if (result.contains(Constant.INTERVAL_SIGN)) {
                        int index = result.indexOf(Constant.INTERVAL_SIGN);
                        holder.setText(R.id.courseA3ItemTextView1, result.substring(0, index) + "\n" +
                                result.substring(index + 1));
                    } else {
                        holder.setText(R.id.courseA3ItemTextView1, result);
                    }
                    map.put(data + Constant.LEFT, answerId);
                } else if (Constant.RIGHT.equals(type)) {
                    if (result.contains(Constant.INTERVAL_SIGN)) {
                        int index = result.indexOf(Constant.INTERVAL_SIGN);
                        holder.setText(R.id.courseA3ItemTextView2, result.substring(0, index) + "\n" +
                                result.substring(index + 1));
                    } else {
                        holder.setText(R.id.courseA3ItemTextView2, result);
                    }
                    map.put(data + Constant.RIGHT, answerId);
                }
            }
        });
        if (activity.hasWindowFocus()) {
            courseA1Dialog.show();
        }
    }

    class ClickAble implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.titleLayoutNextTextView:

                    dialogShowListener.dialogShow(1, courseIndex, resultMap());
                    courseInterface.courseInterfaceResult(Constant.NEXT_KNOWLEDGE, courseIndex + 1);
                    break;
                case R.id.titleLayoutLastTextView:
                    dialogShowListener.dialogShow(1, courseIndex, resultMap());
                    courseInterface.courseInterfaceResult(Constant.LAST_KNOWLEDGE, courseIndex - 1);
                    break;
                case R.id.titleLayoutNumberRl:
                    dialogShowListener.dialogShow(1, courseIndex, resultMap());
                    dialogShowListener.dialogShow(0, courseIndex, resultMap());
                    break;
                default:
                    break;
            }
        }
    }

    private boolean resultMap() {

        Constant.getScreen(activity, SPUtil.getSharedPreferencesData(activity, "number") + "_" + (courseIndex + 1),SPUtil.getSharedPreferencesData(activity, "number")+"_"+ (courseIndex + 1));
        if (map != null) {
            boolean result = false;
            score = 0;
            int index = 0;
            for (int i = 0; i < answerModuleList.size(); i++) {
                if (map.get(i + Constant.CENTER) != null || map.get(i + Constant.LEFT) != null || map.get(i + Constant.RIGHT) != null) {
                    if (map.get(i + Constant.CENTER) != null && map.get(i + Constant.CENTER).equals(answerModuleList.get(i).getCenterId())) {
                        score += Double.valueOf(answerModuleList.get(i).getScore());
                    }

                    if (map.get(i + Constant.LEFT) != null && map.get(i + Constant.LEFT).equals(answerModuleList.get(i).getLeftId())) {
                        score += Double.valueOf(answerModuleList.get(i).getScore()) / 2;
                    }

                    if (map.get(i + Constant.RIGHT) != null && map.get(i + Constant.RIGHT).equals(answerModuleList.get(i).getRightId())) {
                        score += Double.valueOf(answerModuleList.get(i).getScore()) / 2;
                    }
                    index++;
                }
            }
            Log.i(TAG, "index=" + index + "  answerModuleList.size()=" + answerModuleList.size() + " score=" + score);
            SPUtil.setSharedPreferencesData(activity.getApplicationContext(), CourseA3.class.getSimpleName(), score + "");
            if (index == answerModuleList.size()) {
                result = true;
            }
            return result;
        } else {
            SPUtil.setSharedPreferencesData(activity.getApplicationContext(), CourseA3.class.getSimpleName(), "0");
            return false;
        }
    }

    @Override
    public void setCourseInterface(CourseInterface courseInterface) {
        this.courseInterface = courseInterface;
    }

    @Override
    public void setCourseDialogListener(DialogShowListener dialogListener) {
        this.dialogShowListener = dialogListener;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

    }

    @Override
    public void show(List<TestModule> courseEntities, int index, String type) {
        initViewData();
    }

    @Override
    public void stop() {

    }

    @Override
    public void destroy() {

    }
}
